package com.bx.implatform.util;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 获取真实Ip地址
 * @author zyl
 */
public class ClientIpUtil {

    public static String getClientRealIp(HttpServletRequest request) {
        String unknown = "unknown";
        String clientIp = request.getHeader("X-Forwarded-For");
        if (clientIp != null && clientIp.length() != 0 && !"unknown".equalsIgnoreCase(clientIp)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if( clientIp.indexOf(",")!=-1 ){
                clientIp = clientIp.split(",")[0];
            }
        }
        if (clientIp == null || clientIp.length() == 0 ||unknown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("Proxy-Client-IP");
        }
        if (clientIp == null || clientIp.length() == 0 || unknown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if (clientIp == null || clientIp.length() == 0 || unknown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (clientIp == null || clientIp.length() == 0 || unknown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_X_FORWARDED");
        }
        if (clientIp == null || clientIp.length() == 0 || unknown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
        }
        if (clientIp == null || clientIp.length() == 0 || unknown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_CLIENT_IP");
        }
        if (clientIp == null || clientIp.length() == 0 || unknown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_FORWARDED_FOR");
        }
        if (clientIp == null || clientIp.length() == 0 || unknown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_FORWARDED");
        }
        if (clientIp == null || clientIp.length() == 0 || unknown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }
        return clientIp;
    }

}
